package com.b2b.message.admin.controller.auth.mail;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.b2b.bean.ResultBase;
import com.b2b.bean.ResultBean;
import com.b2b.constant.ResultEnum;
import com.b2b.message.admin.controller.SuperController;
import com.b2b.message.admin.plus.entity.MailConfig;
import com.b2b.message.admin.plus.entity.MailLogger;
import com.b2b.message.admin.plus.entity.MailTemplate;
import com.b2b.utils.Tools;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

/**
 * 版权：上海极和信息科技有限公司
 * 功能：邮箱配置
 * 作者：朱伟峰
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2018年4月3日
 */
@Controller
@RequestMapping("/mail")
public class MailController extends SuperController
{
	private static final Logger logger = LoggerFactory.getLogger(MailController.class);
	
	@RequestMapping(value = "/conf/view")
	public String confView()
	{
		return "/mail/conf/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/list")
	public ResultBean<Page<MailConfig>> confList()
	{
		Page<MailConfig> page = super.getPageInfo("sort", true);
		EntityWrapper<MailConfig> wrapper = new EntityWrapper<MailConfig>();
		String accessKeyId = request.getParameter("accessKeyId");
		if (!Tools.isTrimEmpty(accessKeyId))
			wrapper.like("accessKeyId", accessKeyId);
		String accessKeySecret = request.getParameter("accessKeySecret");
		if (!Tools.isTrimEmpty(accessKeySecret))
			wrapper.like("accessKeySecret", accessKeySecret);
		String notice = request.getParameter("notice");
		if (!Tools.isTrimEmpty(notice))
			wrapper.like("notice", notice);
		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		String region = request.getParameter("region");
		if (!Tools.isTrimEmpty(region))
			wrapper.and("region={0}", region);
		
		ResultBean<Page<MailConfig>> result = new ResultBean<Page<MailConfig>>();
		try
		{
			Page<MailConfig> pageInfo = mailConfigService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/conf/detail")
	public String confDetail(@RequestParam("accessKeyId") String accessKeyId)
	{
		try
		{
			MailConfig mailConfig = mailConfigService.selectById(accessKeyId);
			if (mailConfig != null)
				request.setAttribute("bean", mailConfig);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/mail/conf/detail";
	}
	
	@RequestMapping(value = "/conf/addView")
	public String confAddView()
	{
		String accessKeyId = request.getParameter("accessKeyId");
		try
		{
			if (!Tools.isTrimEmpty(accessKeyId))
			{
				MailConfig mailConfig = mailConfigService.selectById(accessKeyId);
				if (mailConfig != null)
					request.setAttribute("bean", mailConfig);
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/mail/conf/view";
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/add")
	public ResultBase confAdd(@Valid MailConfig mailConfig)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			Integer status = mailConfig.getStatus();
			if (status == null) 
				mailConfig.setStatus(9);
			
			MailConfig _mailConfig = mailConfigService.selectById(mailConfig.getAccessKeyId());
			if (_mailConfig == null){
				mailConfig.setCreateTime(System.currentTimeMillis());
				mailConfig.setCreateUser(0l);
			}
			mailConfig.setUpdateTime(System.currentTimeMillis());
			mailConfig.setUpdateUser(0l);
			
			boolean flag = mailConfigService.insertOrUpdate(mailConfig);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/del")
	public ResultBase confDel(@RequestParam("accessKeyId") String accessKeyId, @RequestParam("status") int status)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			MailConfig mailConfig = mailConfigService.selectById(accessKeyId);
			if (mailConfig == null)
			{
				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
				return result;
			}
			mailConfig.setStatus(status);
			boolean flag = mailConfigService.insertOrUpdate(mailConfig);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/delAll")
	public ResultBase confDelAll(@RequestParam("accessKeyId") String accessKeyIds)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			String message = "";
			String[] _accessKeyId = accessKeyIds.split(",");
			if (_accessKeyId != null && _accessKeyId.length > 0)
			{
				int i = 0;
				for (String accessKeyId : _accessKeyId)
				{
					i ++;
					MailConfig mailConfig = mailConfigService.selectById(accessKeyId);
					if (mailConfig == null)
					{
						message += "第" + i + "条记录不存在,";
						continue;
					}
					mailConfig.setStatus(9);
					boolean flag = mailConfigService.insertOrUpdate(mailConfig);
					if (!flag) {
						message += "第" + i + "条记录保存失败,";
						continue;
					}
				}
			}
			if (Tools.isTrimEmpty(message)){
				result.success();
			} else{
				result.fail(ResultEnum.ERROR.getCode(), message);
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/** ************************************************** 邮箱消息模板相关接口 ************************************************** */
	
	@RequestMapping(value = "/temp/view")
	public String tempView()
	{
		return "/mail/temp/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/list")
	public ResultBean<Page<MailTemplate>> tempList()
	{
		Page<MailTemplate> page = super.getPageInfo("id", true);
		EntityWrapper<MailTemplate> wrapper = new EntityWrapper<MailTemplate>();
		String id = request.getParameter("id");
		if (!Tools.isTrimEmpty(id))
			wrapper.where("id={0}", id);
		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		String accessKeyId = request.getParameter("accessKeyId");
		if (!Tools.isTrimEmpty(accessKeyId))
			wrapper.like("accessKeyId", accessKeyId);
		String subject = request.getParameter("subject");
		if (!Tools.isTrimEmpty(subject))
			wrapper.like("subject", subject);
		String notice = request.getParameter("notice");
		if (!Tools.isTrimEmpty(notice))
			wrapper.like("notice", notice);
		
		ResultBean<Page<MailTemplate>> result = new ResultBean<Page<MailTemplate>>();
		try
		{
			Page<MailTemplate> pageInfo = mailTemplateService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/temp/detail")
	public String tempDetail(@RequestParam("id") long id)
	{
		try
		{
			MailTemplate mailTemplate = mailTemplateService.selectById(id);
			if (mailTemplate != null)
				request.setAttribute("bean", mailTemplate);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/mail/temp/detail";
	}
	
	@RequestMapping(value = "/temp/addView")
	public String tempAddView()
	{
		String id = request.getParameter("id");
		try
		{
			if (!Tools.isTrimEmpty(id))
			{
				MailTemplate mailTemplate = mailTemplateService.selectById(id);
				if (mailTemplate != null)
					request.setAttribute("bean", mailTemplate);
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/mail/temp/view";
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/add")
	public ResultBase tempAdd(@Valid MailTemplate mailTemplate)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			Integer status = mailTemplate.getStatus();
			if (status == null) 
				mailTemplate.setStatus(9);
			
			if (mailTemplate.getId() == null){
				mailTemplate.setCreateTime(System.currentTimeMillis());
				mailTemplate.setCreateUser(0l);
			}
			mailTemplate.setUpdateTime(System.currentTimeMillis());
			mailTemplate.setUpdateUser(0l);
			
			boolean flag = mailTemplateService.insertOrUpdate(mailTemplate);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/del")
	public ResultBase tempDel(@RequestParam("id") long id, @RequestParam("status") int status)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			MailTemplate mailTemplate = mailTemplateService.selectById(id);
			if (mailTemplate == null)
			{
				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
				return result;
			}
			mailTemplate.setStatus(status);
			boolean flag = mailTemplateService.insertOrUpdate(mailTemplate);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/** ************************************************** 邮箱日志相关接口 ************************************************** */
	
	@RequestMapping(value = "/logs/view")
	public String logsView()
	{
		return "/mail/logs/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/logs/list")
	public ResultBean<Page<MailLogger>> logsList()
	{
		Page<MailLogger> page = super.getPageInfo("id", false);
		EntityWrapper<MailLogger> wrapper = new EntityWrapper<MailLogger>();

		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		String toAddress = request.getParameter("toAddress");
		if (!Tools.isTrimEmpty(toAddress))
			wrapper.and("toAddress={0}", toAddress);
		String code = request.getParameter("code");
		if (!Tools.isTrimEmpty(code))
		{
			if ("OK".equals(code)) wrapper.eq("code", 0);
			else wrapper.ne("code", 0);
		}
		String mailTempId = request.getParameter("mailTempId");
		if (!Tools.isTrimEmpty(mailTempId))
			wrapper.and("mailTempId={0}", mailTempId);
		
		ResultBean<Page<MailLogger>> result = new ResultBean<Page<MailLogger>>();
		try
		{
			Page<MailLogger> pageInfo = mailLoggerService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/logs/detail")
	public String logsDetail(@RequestParam("id") long id)
	{
		try
		{
			MailLogger mailLogger = mailLoggerService.selectById(id);
			if (mailLogger != null)
				request.setAttribute("bean", mailLogger);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/mail/logs/detail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/listType")
	public ResultBean<List<Map<String, Object>>> confListType()
	{
		ResultBean<List<Map<String, Object>>> result = new ResultBean<List<Map<String, Object>>>();
		
		try
		{
			EntityWrapper<MailConfig> wrapper = new EntityWrapper<MailConfig>();
			wrapper.where("status={0}", 0);
			wrapper.orderBy("sort", true);
			List<Map<String, Object>> list = mailConfigService.selectMaps(wrapper);
			if (list != null && !list.isEmpty())
			{
				result.success(list);
			}
			else
			{
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
}
